import { expect } from '@jest/globals';
import * as compressing from 'compressing';
import fsExtra from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

async function isHapExist(productName: string, moduleRootPath: string) {
  const exist = await fsExtra.pathExists(
    path.resolve(moduleRootPath, `build/${productName}/outputs/default/entry-default-unsigned.hap`));
  return exist;
}

async function isAbcExist(productName: string, moduleRootPath: string) {
  const exist = await fsExtra.pathExists(
    path.resolve(moduleRootPath, `build/${productName}/intermediates/loader_out/default/ets/modules.abc`));
  return exist;
}

async function isMapExist(productName: string, moduleRootPath: string) {
  const exist = await fsExtra.pathExists(
    path.resolve(moduleRootPath, `build/${productName}/intermediates/loader_out/default/ets/sourceMaps.map`));
  return exist;
}

async function isAppExist(projectRootPath: string) {
  const exist = await fsExtra.pathExists(
    path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-unsigned.app'));
  return exist;
}

async function unCompressApp(productName: string, projectRootPath: string) {
  await fsExtra.copyFile(
    path.resolve(projectRootPath, `build/outputs/${productName}/myapplication-default-unsigned.app`),
    path.resolve(projectRootPath, `build/outputs/${productName}/myapplication-default-unsigned.zip`));
  await compressing.zip.uncompress(
    path.resolve(projectRootPath, `build/outputs/${productName}/myapplication-default-unsigned.zip`),
    path.resolve(projectRootPath, `build/outputs/${productName}/myapplication-default-unsigned`));

  await fsExtra.copyFile(
    path.resolve(projectRootPath, `build/outputs/${productName}/myapplication-default-unsigned/entry-default.hap`),
    path.resolve(projectRootPath, `build/outputs/${productName}/myapplication-default-unsigned/entry-default.zip`));
  await compressing.zip.uncompress(
    path.resolve(projectRootPath, `build/outputs/${productName}/myapplication-default-unsigned/entry-default.zip`),
    path.resolve(projectRootPath, `build/outputs/${productName}/myapplication-default-unsigned//entry-default`));

}

async function isAbcExistUnderHapInApp(productName: string, projectRootPath: string) {
  const exist = await fsExtra.pathExists(
    path.resolve(projectRootPath,
      `build/outputs/${productName}/myapplication-default-unsigned//entry-default/ets/modules.abc`));
  return exist;
}

async function isMapExistUnderHapInApp(productName: string, projectRootPath: string) {
  const exist = await fsExtra.pathExists(
    path.resolve(projectRootPath,
      `build/outputs/${productName}/myapplication-default-unsigned//entry-default/ets/sourceMaps.map`));
  return exist;
}


const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const commandHap = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
  });
  const commandApp = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp'
  });
  const commandAppDebug = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp',
    buildMode: 'debug'
  });
  const commandAppRelease = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp',
    buildMode: 'release'
  });
  const commandDebug = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap',
    buildMode: 'debug'
  });
  const commandRelease = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap',
    buildMode: 'release'
  });
  const commandClean = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'clean'
  });
  const commandCleanProject = initExecuteCommand({
    product: 'default',
    tasks: 'clean'
  });
  const moduleRootPath = project.getModule('entry').moduleRootPath();

  // product选择buildMode为<None>,构建hap
  const resultHapDefault = await runHvigorAsync(projectRootPath, commandHap);
  record.addStep('product选择buildMode为None,构建hap', resultHapDefault);
  expect(resultHapDefault.stdout).toContain('Finished :entry:default@PackageHap');
  expect(resultHapDefault.stdout).toContain('BUILD SUCCESSFUL');

  // 判断buildMode为<None>时build hap的产物
  expect(await isHapExist('default', moduleRootPath)).toBe(true);
  expect(await isAbcExist('default', moduleRootPath)).toBe(true);
  expect(await isMapExist('default', moduleRootPath)).toBe(true);

  // product选择buildMode为<None>, 构建App
  const resultAppDefault = await runHvigorAsync(projectRootPath, commandApp);
  record.addStep('product选择buildMode为None,构建App', resultAppDefault);
  expect(resultAppDefault.stdout).toContain('Finished ::PackageApp');
  expect(resultAppDefault.stdout).toContain('BUILD SUCCESSFUL');

  // 判断buildMode为<None>时build App的产物
  expect(await isAppExist(projectRootPath)).toBe(true);

  // 解压app包
  await unCompressApp('default', projectRootPath);
  expect(await isAbcExistUnderHapInApp('default', projectRootPath)).toBe(true);
  await runHvigorAsync(projectRootPath, commandClean);

  // product选择buildMode为<debug>,构建hap
  const resultHapDebug = await runHvigorAsync(projectRootPath, commandDebug);
  record.addStep('product选择buildMode为debug,构建hap', resultHapDebug);
  expect(resultHapDebug.stdout).toContain('Finished :entry:default@PackageHap');
  expect(resultHapDebug.stdout).toContain('BUILD SUCCESSFUL');

  // 判断buildMode为<debug>时build hap的产物
  expect(await isHapExist('default', moduleRootPath)).toBe(true);
  expect(await isAbcExist('default', moduleRootPath)).toBe(true);
  expect(await isMapExist('default', moduleRootPath)).toBe(true);

  // product选择buildMode为<debug>, 构建App
  await runHvigorAsync(projectRootPath, commandCleanProject);
  const resultAppDebug = await runHvigorAsync(projectRootPath, commandAppDebug);
  record.addStep('product选择buildMode为debug,构建App', resultAppDebug);
  expect(resultAppDebug.stdout).toContain('Finished ::PackageApp');
  expect(resultAppDebug.stdout).toContain('BUILD SUCCESSFUL');

  // 判断buildMode为<debug>时build App的产物
  expect(await isAppExist(projectRootPath)).toBe(true);

  // 解压app包
  await unCompressApp('default', projectRootPath);
  expect(await isAbcExistUnderHapInApp('default', projectRootPath)).toBe(true);
  expect(await isMapExistUnderHapInApp('default', projectRootPath)).toBe(true);
  await runHvigorAsync(projectRootPath, commandClean);

  // product选择buildMode为<release>,构建hap
  const resultHapRelease = await runHvigorAsync(projectRootPath, commandRelease);
  record.addStep('product选择buildMode为release,构建hap', resultHapRelease);
  expect(resultHapRelease.stdout).toContain('Finished :entry:default@PackageHap');
  expect(resultHapRelease.stdout).toContain('BUILD SUCCESSFUL');

  // 判断buildMode为<release>时build hap的产物
  expect(await isHapExist('default', moduleRootPath)).toBe(true);
  expect(await isAbcExist('default', moduleRootPath)).toBe(true);

  // product选择buildMode为<release>, 构建App
  await runHvigorAsync(projectRootPath, commandCleanProject);
  const resultAppRelease = await runHvigorAsync(projectRootPath, commandAppRelease);
  record.addStep('product选择buildMode为release,构建App', resultAppRelease);
  expect(resultAppRelease.stdout).toContain('Finished ::PackageApp');
  expect(resultAppRelease.stdout).toContain('BUILD SUCCESSFUL');

  // 判断buildMode为<release>时build App的产物
  expect(await isAppExist(projectRootPath)).toBe(true);

  // 解压app包
  await unCompressApp('default', projectRootPath);
  expect(await isAbcExistUnderHapInApp('default', projectRootPath)).toBe(true);

};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_ZOS_CONFIGURATION_FILE_CANONICALIZATION_HOS_API10_STAGE_012')
  .description('选择默认buildMode为<None>、debug、release')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
